#include <iostream>
#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include "opencv2/imgproc/imgproc_c.h"
#include "opencv2/highgui/highgui.hpp"

int main() {
    for(unsigned int m=0; m<1; m++) {
        cv::Mat sourceImage = cv::imread("../test1.jpg");
        cv::Mat YUVImage = sourceImage.clone();
        cv::Mat YUV[3], RGB[3];
        cv::cvtColor(sourceImage, YUVImage, cv::COLOR_BGR2YUV);
        cv::split(YUVImage, YUV);
        cv::split(sourceImage, RGB);
        cv::threshold(RGB[2], RGB[2], 200, 255, 0);
        cv::imwrite("RGB.jpg", RGB[2]);
        cv::threshold(RGB[2], RGB[2], 0, 150, 0);
        cv::threshold(RGB[2], RGB[2], 0, 150, 0);
        cv::resize(RGB[2], RGB[2], RGB[2].size() / 2);
        cv::imshow("RED", RGB[2]);
        cv::Mat destinyImage = cv::Mat(sourceImage.size(), CV_8UC1);
        for (unsigned int i = 0; i < sourceImage.rows; i++) {
            for (unsigned int j = 0; j < sourceImage.cols; j++) {
                if (YUV[2].at<uchar>(i, j) > 160) {
                    destinyImage.at<uchar>(i, j) = 255;
                } else {
                    destinyImage.at<uchar>(i, j) = 0;
                }
            }
        }
        std::vector<std::vector<cv::Point> > contours;
        std::vector<cv::Vec4i> hierarchy;
        cv::findContours(destinyImage, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_NONE, cv::Point(0, 0));
        int i=0;
        std::vector<int> recorder;
        for(auto h : hierarchy) {
            if(h[2] == -1 && h[3] != -1) {
                recorder.push_back(i);
            }
            i++;
        }
        std::vector<std::vector<cv::Point> > newContours;
        for(auto j : recorder) {
            newContours.push_back(contours.at(j));
            std::cout << j << std::endl;
            /*for (const auto &point : contours.at(j)) {
                cv::circle(sourceImage, point, 1, cv::Scalar(0, 0, 255), 1);
            }*/
        }
        drawContours(sourceImage, newContours, 0, cv::Scalar(255, 0, 0), CV_FILLED);
        drawContours(sourceImage, newContours, 1, cv::Scalar(255, 0, 0), CV_FILLED);
        cv::imwrite("../result.jpg", destinyImage);
        cv::imwrite("../draw.jpg", sourceImage);
        cv::resize(destinyImage, destinyImage, destinyImage.size() / 2, 0, 0, cv::INTER_LINEAR);
        cv::resize(sourceImage, sourceImage, sourceImage.size() / 2, 0, 0, cv::INTER_LINEAR);
        cv::imshow("des", destinyImage);
        cv::imshow("src", sourceImage);
        cv::waitKey(0);
    }
}